﻿#if defined(_MSC_VER) && (_MSC_VER >= 1600)
# pragma execution_character_set("utf-8")
#endif

#include "largefileuploadcontroller.h"

#include <QJsonDocument>
#include <largefileupload.h>
#include <largefileuploadservice.h>

LargeFileUploadController::LargeFileUploadController(QObject *parent)
    : HttpRequestHandler(parent)
{
}

LargeFileUploadController::~LargeFileUploadController()
{
}

void LargeFileUploadController::service(HttpRequest &request, HttpResponse &response)
{
    QString path = request.getPath();
    QStringList pathList = path.split("/");
    if (pathList.size() < 3)
    {
        this->returnError(response);
        return;
    }
    QString method = pathList.value(3);
    QByteArray responseMsg;
    QString methodType = request.getMethod();

    if (methodType == "GET")
    {
        if (method == "getFileInfo")
        {
            return getFileInfo(request, response);
        }
    }
    else if (methodType == "POST")
    {
        if (method == "uploadFileData")
        {
            return uploadFileData(request, response);
        }
    }
    this->returnError(response);
}

void LargeFileUploadController::getFileInfo(HttpRequest &request, HttpResponse &response)
{
    bool success = false;
    QJsonObject jsonObj;
    QByteArray byteArray = request.getParameter("largeFileUpload");
    if (!byteArray.isEmpty())
    {
        LargeFileUpload largeFileUpload = LargeFileUpload::fromJson(byteArray);
        if (largeFileUpload.getMd5().isEmpty())
        {
            jsonObj.insert("success", false);
            jsonObj.insert("error", "文件MD5不可为空");
        }
        else
        {
            LargeFileUploadService LargeFileUploadService;
            QString md5 = largeFileUpload.getMd5();
            QString fileName = largeFileUpload.getFileName();
            qDebug()<< "LargeFileUpload.getTotalSize()" << largeFileUpload.getTotalSize();

            if(!LargeFileUploadService.selectLargeFileUploadByMd5(largeFileUpload,md5)){
                //创建文件
                QString fileDir = "E:/ZetaFileUploadDir";
                QString filePath = QString("%1/%2.bin").arg(fileDir).arg(md5);
                largeFileUpload.setAbsolutePath(filePath);
                //数据库添加记录
                if(LargeFileUploadService.saveLargeFileUpload(largeFileUpload)){
                    //判断文件是否存在，存在读取文件大小
                    QFile fileInfo(largeFileUpload.getAbsolutePath());
                    if(fileInfo.exists()){
                        largeFileUpload.setUploadedSize(fileInfo.size());
                    }
                    success = true;
                    jsonObj.insert("largeFileUpload", QJsonDocument::fromJson(LargeFileUpload::toJson(largeFileUpload)).object());
                }else{
                    jsonObj.insert("error", "创建上传记录失败!");
                }
            }else{
                //判断文件是否存在，存在读取文件大小
                QFile fileInfo(largeFileUpload.getAbsolutePath());
                if(fileInfo.exists()){
                    largeFileUpload.setUploadedSize(fileInfo.size());
                }
                success = true;
                jsonObj.insert("largeFileUpload", QJsonDocument::fromJson(LargeFileUpload::toJson(largeFileUpload)).object());
            }
        }
    }
    else
    {
        jsonObj.insert("error", "请求参数未找到!");
    }
    jsonObj.insert("success", success);

    QByteArray responseMsg;
    responseMsg = QJsonDocument(jsonObj).toJson();
    response.write(responseMsg);
}

void LargeFileUploadController::uploadFileData(HttpRequest &request, HttpResponse &response)
{
    bool success = false;
    QJsonObject jsonObj;

    QTemporaryFile *largeFileUploadTemporaryFile = request.getUploadedFile("largeFileUpload");
    QTemporaryFile *chunkFileTemporaryFile = request.getUploadedFile("chunkFile");

    QByteArray LargeFileUploadByteArray = largeFileUploadTemporaryFile->readAll();
    if (!LargeFileUploadByteArray.isEmpty())
    {
        LargeFileUpload largeFileUpload = LargeFileUpload::fromJson(LargeFileUploadByteArray);
        if(!largeFileUpload.getAbsolutePath().isEmpty()){
            QFile file(largeFileUpload.getAbsolutePath());
            if(file.open(QIODevice::ReadWrite | QIODevice::Append)){
                file.seek(largeFileUpload.getUploadedSize() == 0 ?  0 : largeFileUpload.getUploadedSize() - 1);
                file.write(chunkFileTemporaryFile->readAll());
                largeFileUpload.setUploadedSize(file.size());
                file.close();
                if(largeFileUpload.getUploadedSize() >= largeFileUpload.getTotalSize()){
                    largeFileUpload.setUploadStatus(1);
                    LargeFileUploadService LargeFileUploadService;
                    LargeFileUploadService.saveLargeFileUpload(largeFileUpload);
                }
                success = true;
                jsonObj.insert("largeFileUpload", QJsonDocument::fromJson(LargeFileUpload::toJson(largeFileUpload)).object());
            }else{
                jsonObj.insert("error", "文件打开失败!");
            }
        }else{
            jsonObj.insert("error", "文件地址不可为空!");
        }
    }else{
        jsonObj.insert("error", "请求参数未找到!");
    }
    jsonObj.insert("success", success);
    QByteArray responseMsg;
    responseMsg = QJsonDocument(jsonObj).toJson();
    response.write(responseMsg);
}
